/**
 * Created by Administrator on 2016/3/16.
 */

var SPSdk = (function () {
    //var SDK = "http://res.imtt.qq.com/html5game/api/js/qbh5-1.0.0-min.js";
    var SDK = "http://jsapi.qq.com/get?api=x5gameplayer.*";
    var getSign = "http://paycenter.layabox.com/pay/3/GetX5Sign?orderId=";
    var qqsdk = null, self = null;

    function SPSdk() {
        this.layaStorage = new LayaStorageH5("LAYA_H5_SP_LOCAL_INFO");
        this.access_token = "";
        this.appId = "";
        this.appKey = "";
        this.loginKey = "";
        this.openId = "";
        this.openKey = "";
        this.payKey = "";
        this.spFname = "";
        this.spId = 0;

        this.qbopenid = "";
        this.qbopenkey = "";
        this.loginType = "";
        this.refreshkey = "";

        this.loginResult = null;

        self = this;
    }

    function getAvailableLoginType(callback) {
        qqsdk && qqsdk.getAvailableLoginType({"appid": self.appId}, function (param) {
            callback && callback({result: 1000, desc: "need available login type",data:{"loginType":2}, availableData: param});
        });
    }

    function refreshToken(callback) {
        qqsdk && qqsdk.refreshToken({
            "appid": self.appId,
            "qbopenid": self.qbopenid,
            "refreshToken": self.refreshkey
        }, function (param) {
            console.log(JSON.stringify(param));
            if (param.result == 0) {
                self.layaStorage.setLocalStore("X5_QB_OPENKEY", param.qbopenkey);
                var user = LayaStruct.spLoginInfo();
                user.result = 0;
                user.spuid = self.qbopenid;
                user.sessionKey = param.qbopenkey;
                user.type =  self.loginType;//特殊处理

                callback && callback(user);
            }
            else {
                getAvailableLoginType(callback);
            }
        });
    }

    function x5Login(callback) {
        var data = {
            "appid": self.appId,
            "appsig": self.signkey,
            "appsigData": self.signdata,
            "loginType": self.loginType
        };
        console.log(JSON.stringify(data));
        qqsdk && qqsdk.login(data, function (param) {
            console.log(JSON.stringify(param));
            if (param.result == 0) {
                var user = LayaStruct.spLoginInfo();

                user.result = 0;
                user.spuid = param.qbopenid;
                user.nickName = param.nickName;
                user.avatarUrl = encodeURIComponent(param.avatarUrl);
                user.sessionKey = param.refreshToken;

                user.type =  self.loginType;//特殊处理

                self.qbopenid = param.qbopenid;
                self.qbopenkey = param.qbopenkey;
                self.refreshkey = param.refreshToken;

                self.layaStorage.setLocalStore("X5_LOGIN_TYPE", self.loginType);
                self.layaStorage.setLocalStore("X5_REFRESH_KEY", param.refreshToken);
                self.layaStorage.setLocalStore("X5_QB_OPENID", param.qbopenid);
                self.layaStorage.setLocalStore("X5_QB_OPENKEY", param.qbopenkey);

                callback && callback(user);
            } else {
                callback && callback({result: param.result,data:{"loginType":2},desc: param.msg});
            }
        });
    }

    var __proto = SPSdk.prototype;
    __proto.login = function (param, callback) {
        console.log("X5登录：" + JSON.stringify(param));
        var authorizeType = param["authorizeType"];
        if (!authorizeType) {
            if (!self.refreshkey || !self.qbopenid) {
                console.log("call getAvailableLoginType");
                getAvailableLoginType(callback);
            }
            else {
                console.log("need refresh token");
                refreshToken(callback);
            }
        }
        else {
            console.log("login:" + JSON.stringify(param));
            self.loginType = param.authorizeType;
            x5Login(callback);
        }
    };
    __proto.logout = function (param, callback) {
        console.log("X5登出：" + JSON.stringify(param));
        qqsdk && qqsdk.logout({appid: self.appId, qbopenid: self.qbopenid, loginType: ""}, function (param) {
            self.layaStorage.removeLocalStore("X5_REFRESH_KEY");
            self.layaStorage.removeLocalStore("X5_QB_OPENID");
            self.layaStorage.removeLocalStore("X5_QB_OPENKEY");

            callback && getAvailableLoginType(callback);
        });
    };
    __proto.pay = function (param, callback) {
        console.log("X5充值：" + JSON.stringify(param));
        var m_this = this;
        if (param.ret == 0) {
            LayaCommon.getJson(getSign + param.data.orderId, function (myData) {
                qqsdk && qqsdk.pay({
                    appid: myData.appid,
                    appsig: "",
                    paysig: myData.paysig,
                    qbopenid: myData.qbopenid,
                    qbopenkey: myData.qbopenkey,
                    payItem: myData.payItem,
                    payInfo: myData.payInfo,
                    reqTime: myData.reqTime,
                    customMeta: myData.customMeta
                }, function (rsp) {
                    callback && callback(rsp);
                });
            });
        }
    };
    __proto.getGameFriends = function (param, callback) {
        var m_this = this;
        qqsdk && qqsdk.getGameFriends({
            appid: m_this.appId,
            appsig: "",
            qbopenid: m_this.qbopenid,
            qbopenkey: m_this.qbopenkey
        }, function (data) {
            if (data.result == 0)
            {
                data.friendslist = JSON.stringify(data.friends);
                callback && callback(JSON.stringify(data))
            }
            else if(data.result == -4)
            {

            }else
            {
                callback && callback(JSON.stringify({result:data.result,desc:data.msg}))
            }
        });
    };
    __proto.share = function (param, callback) {
        var m_this = this;
        qqsdk && qqsdk.share({
            url: param.link,
            title: param.title,
            description: param.content,
            imgUrl: param.imgUrl,
            imgTitle: param.imgtitle,
            cusTxt: param.custxt,
            toApp: param.toApp
        }, function (rsp) {
            callback && callback(JSON.stringify(rsp));
        });
    };
    __proto.openQb = function (param, callback) {

    };
    __proto.sendToDesktop = function (param, callback) {
        qqsdk && qqsdk.sendToDesktop(param, function (res) {
            callback && callback(JSON.stringify({result: res.result, desc: res.msg}));
        });
    };
    __proto.canSendToDesktop = function (param) {
        return true;
    };
    __proto.openTopicCircle = function (param, callback) {
        var m_this = this;
        qqsdk && qqsdk.openTopicCircle(this.appId, function (res) {
            callback && callback(JSON.stringify({result: res.result, desc: res.msg}));
        })
    };
    __proto.getUserInfo = function (param, callback) {
        var m_this = this;
        qqsdk.getUserInfo && qqsdk.getUserInfo({
            appid: m_this.appId,
            qbopenid: m_this.qbopenid,
            qbopenkey: m_this.qbopenkey
        }, function (rsp) {
            //data.result //result为0获取成功，否则失败
            //data.msg //传回的提示信息
            //data.nickName //用户昵称
            //data.avatarUrl //用户头像url
            //data.sex// 性别：0未知，1男，2女
            //data.city //城市
            //data.language //语言
            //data.isVip// 是否为vip
            //data.province// 省份
            //data.country// 国家
            //data.birthday //生日，不确定微信手q是否能取到
            callback && callback(JSON.stringify(rsp));
        });
    };
    __proto.init = function (param, callback) {
        console.log("X5初始化：" + JSON.stringify(param));

        self.access_token = param.access_token;
        self.appId = param.appId;
        self.appKey = param.appKey;
        self.loginKey = param.loginKey;
        self.openId = param.openId;
        self.openKey = param.openKey;
        self.payKey = param.payKey;
        self.spFname = param.spFname;
        self.spId = param.sp;

        self.signdata = param.logonKeyInfo.data.signdata;
        self.signkey = param.logonKeyInfo.data.signkey;

        self.loginType = self.layaStorage.getLocalStore("X5_LOGIN_TYPE")||"";
        self.refreshkey = self.layaStorage.getLocalStore("X5_REFRESH_KEY") || "";
        self.qbopenid = self.layaStorage.getLocalStore("X5_QB_OPENID") || "";
        self.qbopenkey = self.layaStorage.getLocalStore("X5_QB_OPENKEY") || "";

        console.log(JSON.stringify(param));
        LayaCommon.loadScript(SDK, function () {
            qqsdk = window.qqsdk = window.browser.x5gameplayer;

            var configData = {
                "loginCallBack": function (rspObj) {
                    self.loginResult = rspObj;
                }
            };
            qqsdk && qqsdk.config(configData);

            callback && callback({"result": 0, "desc": "OK", "sp_data": null});
        })
    };

    return SPSdk;
})();